import React from 'react'
// ===================================================================== 
const { $fn, $http, $Lazy } = window
// ===================================================================== Lazy
const Title		= $Lazy.load(()=>import('#tp/title/title-small'))
const FormItem	= $Lazy.load(()=>import('#cpt/form/submit-item'))
// ===================================================================== data
let list = [
	{ label:'满意', 					name:'1-1',  	line:'line_1',	index:1, 	group:'1' },
	{ label:'见宫颈管/移行区成份', 		name:'1-1-1',	line:'line_1_1',	index:1, 	type:'radio', flag:'1-1' },
	{ label:'未见宫颈管/移行区成份',		name:'1-1-2',	line:'line_1_1',	index:1, 	type:'radio', flag:'1-1' },
	
	{ label:'不满意', 					name:'1-2',	 	line:'line_1',	index:1, 	group:'1'},
	{ label:'上皮细胞数数量偏低', 		name:'1-2-1', 	line:'line_1_1',	index:1, 	type:'radio', flag:'1-2', disabled:true },
	{ label:'血液遮盖超过75%的鳞状细胞', name:'1-2-2', 	line:'line_1_1',	index:1, 	type:'radio', flag:'1-2', disabled:true },
	{ label:'炎性渗出物遮盖', 			name:'1-2-3',	line:'line_1_1',	index:1, 	type:'radio', flag:'1-2', disabled:true },
	
	{ label:'未见', 					name:'2-1', 	line:'line_2',	title:'TBS标准诊断'},
	
	// 一、无上皮内病变或恶性病变
	// 非肿瘤性发现
	{ label:'鳞状细胞化生', 				name:'3-1-1-1', line:'line_3',		index:3, t1:'1、非肿瘤性发现', t2:'(1) 非肿瘤性细胞学改变'},
	{ label:'角化性改变', 				name:'3-1-1-2', line:'line_3',	index:3},
	{ label:'输卵管化生', 				name:'3-1-1-3', line:'line_3',	index:3},
	{ label:'萎缩', 					name:'3-1-1-4', line:'line_3',	index:3},
	{ label:'妊娠相关性改变',	 		name:'3-1-1-5', line:'line_3',	index:3},
	// 反应性细胞改变与下述相关
	{ label:'炎症（包括典型的修复）', 	name:'3-1-2-1', line:'line_3',	index:3, t2:'(2) 反应性细胞改变与下述相关'},
	{ label:'放射治疗', 					name:'3-1-2-2', line:'line_3',	index:3},
	{ label:'宫内节育器（IUD）', 		name:'3-1-2-3', line:'line_3',	index:3},
	
	{ label:'子宫切除后是否有腺细胞', 		name:null, 	index:3, t2:'(3) 子宫切除后是否有腺细胞'},
	// 微生物病原体
	{ label:'滴虫', 						name:'3-2-1', line:'line_3',	index:3, t1:'2、微生物病原体'},
	{ label:'形态符合白色念珠菌', 			name:'3-2-2', line:'line_3',	index:3},
	{ label:'菌群失调，提示细菌性阴道病', 	name:'3-2-3', line:'line_3',	index:3},
	{ label:'形态符合放线菌的细菌', 			name:'3-2-4', line:'line_3',	index:3},
	{ label:'符合单纯疱疹病毒的细胞学改变', 	name:'3-2-5', line:'line_3',	index:3},
	{ label:'符合巨细胞病毒细胞学改变', 		name:'3-2-6', line:'line_3',	index:3},
	// { label:'子宫切除后是否有腺细胞', 		name:'3-2-7', line:'line_3',	index:3},
	// 微生物病原体
	{ label:'子宫内膜细胞（见于>=45岁女性）', name:'3-3-1', line:'line_3',	index:3, t1:'3、其他'},
	
	// 二、上皮细胞异常
	{ label:'非典型鳞状细胞', 					name:'4-1-1', 	line:'line_7',	index:4, 	group:'4-1', t1:'1、鳞状细胞' },
	{ label:'意义不明确（ASC-US）', 				name:'4-1-1-1',	line:'line_7_1',	index:4, 	type:'radio', flag:'4-1-1', disabled:true },
	{ label:'不除外高度鳞状上皮内病变(ASC-H)',	name:'4-1-1-2',	line:'line_7_1',	index:4, 	type:'radio', flag:'4-1-1', disabled:true },
	
	{ label:'低度鳞状上皮内病变(LSIL)\r（包含：HPV/轻度异型增生/CINI）', 			name:'4-1-2', 	line:'line_7',		index:4,  group:'4-1' },
	{ label:'高度鳞状上皮病变(H-SIL)\r（包含：中度及重度异型增生；CIN2及CIN3）', 	name:'4-1-3',	line:'line_7',		index:4,  group:'4-1' },
	{ label:'具有可能浸润的特点（若疑为浸润）',									name:'4-1-3-1',	line:'line_7_1',		index:4, 		type:'radio', flag:'4-1-3', disabled:true },
	
	{ label:'鳞状细胞癌（SCC）',					name:'4-1-4',	line:'line_7',	index:4, group:'4-1' },
	
	// 腺细胞
	{ label:'非典型腺细胞（AGC）', 					name:'4-2-1', 	line:'line_10',		index:4, 	group:'4-2', t1:'2、腺细胞' },
	{ label:'非典型腺细胞，子宫颈管细胞（非特异）', 	name:'4-2-1-1',	line:'line_10_1',	index:4, 	type:'radio', flag:'4-2-1', disabled:true },
	{ label:'非典型腺细胞，子宫内膜细胞（非特异）',	name:'4-2-1-2',	line:'line_10_1',	index:4, 	type:'radio', flag:'4-2-1', disabled:true },
	{ label:'非典型腺细胞（来源不确定）',				name:'4-2-1-3',	line:'line_10_1',	index:4, 	type:'radio', flag:'4-2-1', disabled:true },
	
	{ label:'非典型腺细胞', 							name:'4-2-2', 	line:'line_10',	index:4, 	group:'4-2'},
	{ label:'典型子宫颈管腺细胞（AEC），倾向肿瘤', 	name:'4-2-2-1',	line:'line_10_1',	index:4, 	type:'radio', flag:'4-2-2', disabled:true },
	{ label:'典型腺细胞（AGC），倾向肿瘤',			name:'4-2-2-2',	line:'line_10_1',	index:4, 	type:'radio', flag:'4-2-2', disabled:true },
	
	{ label:'子宫颈管原位癌（AIS）', 				name:'4-2-3', 	line:'line_10',	index:4, 	group:'4-2'},
	
	{ label:'腺癌', 								name:'4-2-4', 	line:'line_10',	index:4, 	group:'4-2',},
	{ label:'子宫颈管腺癌', 							name:'4-2-4-1',	line:'line_10_1',	index:4, 	type:'radio', flag:'4-2-4', disabled:true },
	{ label:'子宫内膜腺癌', 							name:'4-2-4-2',	line:'line_10_1',	index:4, 	type:'radio', flag:'4-2-4', disabled:true },
	{ label:'子宫外腺癌', 							name:'4-2-4-3',	line:'line_10_1',	index:4, 	type:'radio', flag:'4-2-4', disabled:true },
	{ label:'无分类', 								name:'4-2-4-4',	line:'line_10_1',	index:4, 	type:'radio', flag:'4-2-4', disabled:true },
]
// ===================================================================== component
const Index = ({ info={}, result = {}, disabled, form }, ref) => {
	const [ show, setShow ] = React.useState(0)
	const [ data, setData ] = React.useState($fn.copy(list))
	const rsRef = React.useRef({})
	// const formRef = React.useRef({})
	
	// 给表单赋值
	const setFormValue = React.useCallback( rs =>{
		let _result_proposal = ''
		let _suggest = ''
		// 给表单赋值
		Object.keys(rs).forEach((key,i)=>{
			const v = rs[key].data
			// const br = i > 0 ? '\r' : ''
			if ( v['result'] ){
				_result_proposal +=  v['result'] + '\r'
			}
			if( v['notes'] ){
				_suggest	+= v['notes'] +'\r'
			}
		})
		form.current.refs.ref.setValue({ result_proposal: _result_proposal, suggest: _suggest })
	},[form])
	// 接口请求结果
	const setM = React.useCallback( (name, rows, cb) => {
		$http.submit(null,'conf-tct/numKey', { param:{num_key: name} }).then( data =>{
			data = $fn.hasObject(data) ? data : {}
			
			if( rows.name === '1-2' || rows.flag === '1-2'){	// 不满意，不叠加
				rsRef.current = { [name]: { data, rows } }
			}else{
				if( rsRef.current['1-2'] || rsRef.current['1-2-1'] || rsRef.current['1-2-2'] || rsRef.current['1-2-3'] ){	// 去掉不满意
					rsRef.current = { [name]: { data, rows } }
				}else{
					rsRef.current[name] = { data, rows }
				}
			}
			setFormValue(rsRef.current)
			cb && cb()
		})
	},[setFormValue])
	// 初始始加载
	const init = React.useCallback(form => {
		let { forms_check_data, is_menopause, imgs, regroup_data_web, result_proposal } = result || {}
		setShow( +is_menopause !== 1) // 是否绝经
		let my_forms = {}
		let copy_data = forms_check_data
		let copy_list = $fn.copy(list)
		
		// if($fn.hasObject(copy_data)){
		// 	for(let i in copy_data){
		// 		if($fn.isValid(copy_data[i])){
		// 			copy_data[i] = true
		// 		}
		// 	}
		// 	form.setValue({...copy_data, imgs})
		// }else{
		// 	form.setValue({ '1-1':true, '1-1-1':true, '2-1':true })
		// 	setM('2-1', {})
		// }
		let isWeiJian = true
		if($fn.hasArray(copy_data)){
			copy_data.forEach(v=>{
				const key = Object.keys(v)[0]
				const value = v[key]
				if($fn.isValid(value)){
					my_forms[key] = true
				}else{
					my_forms[key] = false
				}
				if(key.indexOf('4-') !== -1){
					if(my_forms['1-2'] || my_forms[key] ){
						isWeiJian = false
						my_forms['2-1'] = false
					}
				}
				// 回显是否禁用
				copy_list.forEach( m => {
					// 当为不满意时, 全部禁用
					if( key === '1-2' && value ){
						copy_list.forEach( n => {
							n.disabled = true
							if(n.flag === key || n.name === key){ // 如果 name,flag 相同的，不禁用
								n.disabled = false
							}
						})
					}
					
					if( m.name === key && value){
						m.disabled = false
						copy_list.forEach( n => {
							if(n.flag === key || n.name === key){ // 如果 name,flag 相同的，不禁用
								n.disabled = false
							}
						})
					}
				})
			})
			if(isWeiJian){
				setM('2-1',{}, result_proposal ? () => form.setValue({ result_proposal }) : null)
				my_forms['2-1'] = true
			}
			setData(copy_list)
			form.setValue({...my_forms, imgs, ts_audit_name:info.ts_audit_name, ts_approve_name:info.ts_approve_name})
			// 加载默认
		}else{
			setData(copy_list)
			form.setValue({ '1-1':true, '1-1-1':true, '2-1':true })
			if($fn.hasObject(info)){
				setM('2-1', {}, result_proposal ? () => form.setValue({ result_proposal }) : null)
			}
		}
		
		// 回显
		rsRef.current = {}
		if(regroup_data_web){
			try{
				let { cussumData } = JSON.parse(regroup_data_web)
				if($fn.hasArray(cussumData)){
					cussumData.forEach( v => rsRef.current[v.num_key]  = { data: v })
				}else{
					cussumData = []
				}
			}catch(e){
				console.error('cussumData 不是标准的 JSON 格式')
			}
		}
		// formRef.current = form
		// setFormValue(rsRef.current)
	},[setM, result, info])
	
	React.useImperativeHandle( ref, () => {
		return {
			data : () => {
				let cussumData = []
				for( let i in rsRef.current){
					const _data = rsRef.current[i]['data']
					if($fn.hasObject(_data)){
						cussumData.push(_data)
					}
				}
				return { 
					list, 
					web: {
						cussumData, 				// 选择的 numKey 数据
						// satisfactionData:{}, 
						// squamousCellData:{},
						// glandCellData:{},
						// notSeeData:{}
					} 
				}
			},
			load: form => init(form)
		}
	})
	
	React.useEffect(()=>{
		
	},[ ])
	// 改变时判断
	const onChange = React.useCallback((rows, {value}) => {
		const { ref } = form.current.refs
		
		if(rows.index === 3 ){ 
			if(value){
				setM(rows.name,  rows)
			}else{
				delete rsRef.current[rows.name]
				setFormValue(rsRef.current)
			}
			return
		}
		
		let bool = null
		// 表单联动
		data.forEach((v,i)=>{
			const { group,  flag, name, type } = v
			if(value){
				// 当点满意与不满意时
				if( (rows.name === '1-1' || rows.name === '1-2')){
					if(group !== 1){	//  启用与禁用其它元素
						if(rows.name === '1-1'){			// 满意时
							v.disabled = flag === '1-2'		// 启用
							
							if(flag === '1-2'){
								ref.setValue({[name]: false, '1-1-1': true })
							}
							ref.setValue({ '2-1':true })
							setM('2-1',  rows)
							setFormValue(rsRef.current)
							// 初始化未见与上皮细胞异常互斥
							if(group && group.indexOf('4-') > -1){
								ref.setValue({[name]: false})
							}
							if(flag && flag.indexOf('4-') > -1 ){
								ref.setValue({[name]: false})
								v.disabled = true
							}
						}else{								// 不满意时
							v.disabled = flag !== '1-2'		// 禁用
							ref.setValue({[name]: false, '1-2-1': true})
							setM('1-2-1',  rows)
						}
					}
				}else{
					if( rows.name === name && rows.flag !== '1-1' ){ setM(rows.name,  rows) }
					// 选父级，禁用启用子级
					if(rows.group && type === 'radio' && flag.indexOf(rows.group) > -1){
						v.disabled = rows.name !== flag
						if(v.disabled){
							ref.setValue({[name]: false })
							delete rsRef.current[name]
							setFormValue(rsRef.current)
						}
					}
				}
				
				//  上皮细胞异常二选一
				if(rows.group === group && group){
					if(rows.name === name){
						ref.setValue({[name]: value })
					}else{
						ref.setValue({[name]: !value})
						delete rsRef.current[name]
						setFormValue(rsRef.current)
					}
				}
				
				// 内部元素二选一
				if( rows.flag === flag && rows.type === 'radio'){
					if(rows.name === name){
						ref.setValue({[name]: value })
					}else{
						ref.setValue({[name]: !value})
						delete rsRef.current[name]
						setFormValue(rsRef.current)
					}
				}
				// 未见判断
				// 让未见不选中
				if( rows.group && rows.group.indexOf('4-') > -1 && name === '2-1' ){
					ref.setValue({[name]: false})
					delete rsRef.current['2-1']
					setFormValue(rsRef.current)
				}
				 // 让上皮细胞异常不选中
				if(rows.name === '2-1'){	
					if(group && group.indexOf('4-') > -1){
						ref.setValue({[name]: false})
						delete rsRef.current[name]
					}
					if(flag && flag.indexOf('4-') > -1 ){
						ref.setValue({[name]: false})
						v.disabled = true
						delete rsRef.current[name]
					}
					
					setFormValue(rsRef.current)
				}
			}else{
				if(rows.group && rows.name === flag){ // 取消 radio 的父组
					ref.setValue({[name]: false})
					v.disabled = true
					delete rsRef.current[name]
					setFormValue(rsRef.current)
				}
				
				// 取消不满意
				if( rows.name === '1-2'){	
					v.disabled = flag === '1-2'		// 禁用未见
					// 不满意取消
					delete rsRef.current['1-2']
					delete rsRef.current['1-2-1']
					delete rsRef.current['1-2-2']
					delete rsRef.current['1-2-3']
					setFormValue(rsRef.current)
					// 未见与上皮细胞异常互斥
					if(group && group.indexOf('4-') > -1){
						ref.setValue({[name]: false})
					}
					if(flag && flag.indexOf('4-') > -1 ){
						ref.setValue({[name]: false})
						v.disabled = true
					}
				}else if(rows.name === '1-1'){
					delete rsRef.current['2-1']
					setFormValue(rsRef.current)
				}else if(rows.name === name){
					if( rows.name === '1-1'){ // 满意取消，删除未见
						delete rsRef.current['2-1']
					}else if(rows.name === '1-2'){ 		// 不满意取消，删除
						delete rsRef.current['1-2']
						delete rsRef.current['1-2-1']
						delete rsRef.current['1-2-2']
						delete rsRef.current['1-2-3']
					}else{
						delete rsRef.current[rows.name]
					}
					setFormValue(rsRef.current)
				}
				
				// 当取消 radio 父级时，则选中未见
				if((rows.group === '4-1' || rows.group === '4-2') && ( group === '4-2' || group === '4-1' )){
					let stack = []
					
					for(let i in rsRef.current){
						const { rows } = rsRef.current[i]
						if(rows && rows.index === 4){
							stack.push(rows)
						}
					}
					
					if(stack.length === 0){
						if(bool === null){
							ref.setValue({'2-1': true})
							setM('2-1',  rows)
							bool = 1
						}
					}
				}
			}
		})
		setData([...data])
	},[form, data, setM, setFormValue]) 
	// 第一部分
	const ListA = React.useCallback( flag =>{
		return (
			<div className='fxm'>
				{
					data.map((v,i) => (
						(v.flag === flag || v.name === flag) && (
							<React.Fragment key={i}>
								{
									v.type === 'radio' ?	<FormItem label={v.label} name={v.name} disabled={disabled||v.disabled} type='checkbox' onChanged={m=>onChange(v,m)}/>
														:	<FormItem style={{width:80}} label={v.label} name={v.name} disabled={disabled} type='checkbox' onChanged={m=>onChange(v,m)}/>
								}
							</React.Fragment>
						)
					))
				}
			</div>
		)
	},[data, disabled, onChange])
	const style = {height:22, lineHeight:22}
	return (
		<div className='wh fv tct-box'>
			<section className='fx rel i10'>
				<div className='ex'>
					<Title title='样本满意度' style={style} />
					{ ListA('1-1') }
					{ ListA('1-2') }
							
					{/* TBS 标准诊断 */}
					<div className='tbor1 mt5'>
						<Title title='TBS 标准诊断' style={style} prefix={
							<FormItem label={data[7].label} mb={0} name={data[7].name} type='checkbox' disabled={disabled || data[7].disabled} onChanged={m=>onChange(data[7],m)}/>
						} />
					</div>
					
					<div className='f12 tbor1 fx checkbox-list'>
						{/* 一、无上皮内病变或恶性病变 */}
						<div className='ex'>
							<Title title='一、无上皮内病变或恶性病变' style={style} />
							{
								data.map((v,i) => (
									v.index === 3 && (
										<React.Fragment key={i}>
											{ v.t1 && <div className='ml10 g6 b'>{v.t1}</div>}
											{ v.t2 && <div className='ml30 lh20 g6 b'>{v.t2}</div>}
											{ v.name && <FormItem style={{marginLeft:30}} key={i} label={v.label} name={v.name} type='checkbox' disabled={disabled||v.disabled} onChanged={m=>onChange(v,m)}/>}
										</React.Fragment>
									)
								))
							}
						</div>
						{/* 二、上皮细胞异常 */}
						<div className='ex'>
							<Title title='二、上皮细胞异常' style={style} />
							{
								data.map((v,i) => (
									v.index === 4 && (
										<React.Fragment key={i}>
											{ v.t1 && <div className='ml10 g6 b' style={{marginBottom:2}}>{v.t1}</div>}
											<FormItem style={{marginLeft:v.type === 'radio' ? 50 : 30}} key={i} label={v.label} name={v.name} type='checkbox' disabled={disabled||v.disabled} onChanged={m=>onChange(v,m)}/>
										</React.Fragment>
									)
								))
							}
						</div>
					</div>
				</div>
				<div className='lbor1 pl10' style={{width:260}}>
					<FormItem title='图形'  name='imgs' type='upload' disabled={disabled} multiple/>
					<div>
						<FormItem label='是否绝经' name='is_menopause' type='checkbox' isNumber disabled={disabled} onChanged={ ({value}) => setShow(!value) }/>
						{
							show ? <FormItem title='末次月经时间' name='last_menstrual_period' type='date-time' after format={1} disabled={disabled}/> : null
						}
					</div>
					{ 
						[45003,45004].includes(+info?.status) && (
							<>
								<FormItem title='初诊医生'  name='ts_audit_name' disabled={true} p='--'/>
								<FormItem title='复诊医生'  name='ts_approve_name' disabled={true} p='--'/>
							</>
						)
					}
				</div>
			</section>
			<div className='fx ex tbor1 rel ptb5 big-font'>
				<div className='ex fv h'>
					<div className='fx ex mr10'>
						<Title title='判读意见/结果' style={style} />
						<div className='ex fv'>
							<FormItem label='判读意见/结果' name='result_proposal' rows={5} wrapClassName='ex ml10 fv ex full-textarea' mode='textarea' disabled={disabled}/>
							<FormItem p='手动输入结果' name='result_proposal_hand' rows={3} wrapClassName='ex ml10 fv ex full-textarea mt5' mode='textarea' disabled={disabled}/>
						</div>
					</div>
				</div>
				<div className='ex fv h'>
					<div className='fx ex mr10'>
						<Title title='附注/建议' style={style} />
						<FormItem label='附注/建议' name='suggest' rows={6} wrapClassName='ex ml10 fv ex full-textarea' mode='textarea' disabled={disabled}/>
					</div>
				</div>
			</div>
		</div>
	)
}

export default Index